package com.mud.dnd.ejb;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionManagement;

import com.mud.dnd.domain.common.DAOException;
import com.mud.dnd.domain.common.QueryParameter;
import com.mud.dnd.domain.dao.DnDDAO;
import com.mud.dnd.domain.model.Card;
import com.mud.dnd.domain.model.Deck;
import com.mud.dnd.domain.model.User;
import com.mud.dnd.ejb.common.AuthenticationException;
import com.mud.dnd.ejb.services.AuthenticationService;

@Stateless
@TransactionManagement
public class DeckManager {
	
	
	@EJB
	private DnDDAO dao;
	
	@EJB
	private AuthenticationService userService;

	@TransactionAttribute
	public List<Deck> getDecks(List<QueryParameter> params) {

		List<Deck> decks = dao.getDecks( params);
		
		for(Deck deck : decks)
		{
			List<Integer> cardIDs = new ArrayList<Integer>();
			
			for(Card card :deck.getCards() )
			{
				cardIDs.add(card.getId());
				
				
			}
			deck.setCardIDs(cardIDs);
			
		}
		
		return decks;
	}

	@TransactionAttribute
	public int createDeck(String name, String description, String pictureURL, String userName, String sessionID) throws DAOException, AuthenticationException {
		
		if(!userService.checkSessionForUser(userName, sessionID))
		{
			throw new AuthenticationException("Login required.");
		}
		User author = userService.getUserData(userName);
		
		return dao.createDeck(name, description, pictureURL, author);
	}
	
	@TransactionAttribute
	public void updateDeck(int id,String name, String description, String pictureURL, int rate, String userName, String sessionID) throws DAOException, AuthenticationException {
		
		if(!userService.checkSessionForUser(userName, sessionID))
		{
			throw new AuthenticationException("Login required.");
		}
		if(!userService.checkIfUserIsOwner(userName, id) && !(name==null && description==null && pictureURL==null  && rate!=0 ))
		{
			throw new AuthenticationException("You can edit only your deck.");
			
		}
		
		dao.updateDeck(id, name, description, pictureURL, null, rate);
	}
	
	@TransactionAttribute
	public void deleteDeck(int id , String userName, String sessionID) throws DAOException, AuthenticationException {
		
		if(!userService.checkSessionForUser(userName, sessionID))
		{
			throw new AuthenticationException("Login required.");
		}
		if(!userService.checkIfUserIsOwner(userName, id) )
		{
			throw new AuthenticationException("You can edit only your deck.");
			
		}
		
		
		dao.deleteDeck(id);
	}
	
	

}
